package com.starblink.android.basic.widget

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.view.*
import androidx.viewbinding.ViewBinding
import com.starblink.android.basic.R

class CustomDialog(context: Context?, themeResId: Int) : Dialog(context!!, themeResId) {
    class Builder(private val context: Context) {
        private var contentView: View? = null
        private var canceledOnTouchOutside: Boolean = true
        private var canCancel: Boolean = true


        /**
         * 是否可以关闭dialog 如返回键 点外边
         * false 不能关闭
         * true 可以关闭 默认true
         * 这个优先级最高
         */
        fun setCanCancel(canCancel: Boolean): Builder {
            this.canCancel = canCancel
            return this
        }


        /**
         * 是否点击外部区域关闭dialog
         * false 不能关闭
         * true 可以关闭 默认true
         */
        fun setCanceledOnTouchOutside(canceledOnTouchOutside: Boolean): Builder {
            this.canceledOnTouchOutside = canceledOnTouchOutside
            return this
        }


        fun setContentView(v: View): Builder {
            this.contentView = v
            return this
        }


        fun create(contentView: View): CustomDialog {
            /**
             * 初始化Dialog
             */
            val dialog = CustomDialog(
                context,
                R.style.custom_dialog
            )

            /**
             * 初始化Dialog的布局页面
             */
            /**
             * 将初始化完整的布局添加到dialog中
             */
            dialog.setContentView(contentView)

            if (canCancel) {
                /**
                 * 禁止点击Dialog以外的区域时Dialog消失
                 */
                dialog.setCanceledOnTouchOutside(canceledOnTouchOutside)
            } else {
                /**
                 * 禁用键盘搜索键
                 * https://blog.csdn.net/lk512893708/article/details/51997811
                 */
                dialog.setOnKeyListener { _, keyCode, _ -> keyCode == KeyEvent.KEYCODE_SEARCH }
                dialog.setCancelable(false)
            }
            return dialog
        }
    }
}